import React, { Component } from 'react'
import { Card, Select, Input, Button, Table, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import memoryUtils from "@/utils/memoryUtils"
import LinkButton from '@/components/link-button';
import { reqProducts, reqSearchProducts, reqUpdateStatus } from '@/api';
import { PAGE_SIZE } from '@/utils/constant';
/**
 * product的默认子路由组件
 */
const Option = Select.Option;

export default class ProductHome extends Component {
    constructor(props) {
        super(props)
        this.initColumn();
        this.state = {
            products: [],  //商品的数组
            total: 0,  //商品的总数量
            loading: false,  //是否在加载中
            searchName: "",  //搜索的关键字
            searchType: "productName",  //根据哪个字段搜索
        }
    }
    // 初始化表格列的数组
    initColumn = () => {
        this.columns = [
            {
                title: '商品名称',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '商品描述',
                dataIndex: 'desc',
                key: 'age',
            },
            {
                title: '价格',
                dataIndex: "price",
                render: (price) => '￥' + price  //当前指定了对于的属性，传入的是对应的属性值
            },
            {
                title: '状态',
                width: 100,
                //dataIndex: "status",
                render: (product) => {
                    const { status, _id } = product;
                    const newStatus = status === 1 ? 2 : 1
                    return (
                        <span>
                            <Button type='primary' onClick={()=>this.updateStatus(_id, newStatus)}>
                                {product.status === 1 ? '下架' : '上架'}
                            </Button>
                            <span> {product.status === 1 ? '在售' : '已下架'}</span>
                        </span>
                    )
                }
            },
            {
                title: '操作',
                width: 100,
                render: (product) => {
                    return (
                        <span>
                            {/* 将product对象使用state传递给目标路由组件 */}
                            <LinkButton onClick={() => this.showDetail(product)}>详情</LinkButton>
                            <LinkButton onClick={()=>this.showUpdate(product)}>修改</LinkButton>
                        </span>
                    )
                }
            },
        ];
    }
    //指定页码的列表数据显示
    getProducts = async (pageNum) => {
        this.pageNum=pageNum;  //保存pageNum,让其他方法也可以看到
        this.setState({ loading: true })  //显示loading
        const { searchName, searchType } = this.state;
        //如果搜索有值说明我们要做搜索分页
        let result;
        if (searchName) {
            result = await reqSearchProducts({ pageNum, pageSize: PAGE_SIZE, searchName, searchType })
        } else {
            //一般分页请求
            result = await reqProducts(pageNum, PAGE_SIZE)
        }

        this.setState({ loading: false })  //隐藏loading
        if (result.data.status === 0) {
            //取出分页数据，更新分页状态 ，显示分页的列表
            const { total, list } = result.data.data
            this.setState({
                total,
                products: list
            })
        }
    }

    //展示详情的方法
    showDetail=(product)=>{
        //互缓存product对象====>给detail组件使用
        memoryUtils.product=product
        this.props.history.push("/product/detail")
    }

    //修改页面
    showUpdate=(product)=>{
        memoryUtils.product=product
        this.props.history.push('/product/addupdate') 
    }

    //更新指定商品的状态
    updateStatus=async(productId,status)=>{
        const result=await reqUpdateStatus(productId,status)
        if(result.data.status===0){
            message.success("更新商品成功")
            //更新商品列表
            this.getProducts(this.pageNum)
        }

    }


    componentDidMount() {
        this.getProducts(1)
    }

    render() {
        const { products, total, loading, searchName, searchType } = this.state
        const title = (
            <span>
                <Select value={searchType} style={{ width: 150 }} onChange={value => this.setState({ searchType: value })}>
                    <Option value="productName">按名字搜索</Option>
                    <Option value="productDesc">按描述搜索</Option>
                </Select>
                <Input placeholder='关键字' style={{ width: 150, margin: '0 15px' }} value={searchName} onChange={event => this.setState({ searchName: event.target.value })} />
                <Button type='primary' onClick={() => this.getProducts(1)}>搜索</Button>
            </span>
        )

        const extra = (
            <Button type='primary' icon={<PlusOutlined />} onClick={()=>this.props.history.push('/product/addupdate')}>
                添加商品
            </Button>
        )

        return (
            <Card title={title} extra={extra}>
                <Table dataSource={products} columns={this.columns} rowKey='_id' bordered
                    pagination={{
                        current:this.pageNum,
                        total: total,
                        defaultPageSize: PAGE_SIZE,
                        showQuickJumper: true,
                        onChange: this.getProducts
                    }} loading={loading}
                />
            </Card>
        )
    }
}

/**
 * 1.子组件调用父组件的方法：将父组件的方法以函数属性的形式传递给子组件，子组件就可以调用
 * 2.父组件调用子组件的方法： 在父组件中通过ref得到子组件标签对象(也就是组件对象)调用其方法
 */
